from flask import Blueprint, jsonify, request, g
import json, traceback
from app.db.mongoClient import MongoError
from app.db import dbUserQuery
from loguru import logger
from app.err_no import errno_no

blueprint = Blueprint('user_query', __name__, url_prefix='/api/user')


@blueprint.route('/v1/query', methods=['POST'])
def query():
    '''
    查询所有用户
    '''
    try:
        data = dbUserQuery.queryAllUser()
        return jsonify(errno_no.OK.data({'userList': data}))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    

@blueprint.route('/v1/query_userDiningStall', methods=['POST'])
def query_userDiningStall():
    '''
    查询用户关联的餐厅档口
    '''
    try:
        j_data = json.loads(request.data)
        userName = j_data.get('userName')
        if userName is None or len(userName) <= 0 :
            return jsonify(errno_no.ErrServerParam.data(None))

        res = dbUserQuery.queryUserDiningStall(userName)
        if res is None:
            return jsonify(errno_no.ErrServerDocumentNotExist.data(None))

        return jsonify(errno_no.OK.data(res))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))